<?php
declare (strict_types=1);

namespace app\api\middleware;

use Closure;
use ffhome\frame\traits\JumpTrait;
use think\Request;

class CheckAuth
{
    use JumpTrait;

    /**
     * 状态:需要登陆
     */
    const S_NEED_LOGIN = -2;

    public function handle(Request $request, Closure $next)
    {
        $authConfig = config('auth');
        $authService = authService();
        $currentNode = $authService->currentNode();
        // 直接通过
        if (in_array($currentNode, $authConfig['direct_jump'])) {
            return $next($request);
        }

        $token = request()->server('http_token');
        if (!in_array($token, explode(',', config('app.allow_token')))) {
            $this->json_result([], lang('common.not_auth'), config('code.fail'));
        }

        // 不需要验证登录直接通过
        if (in_array($currentNode, $authConfig['no_login'])) {
            return $next($request);
        }

        $member = currentMember();
        // 没有登录
        if (empty($member['id'])) {
            $this->json_result([], lang('common.login_first'), self::S_NEED_LOGIN);
        }

        return $next($request);
    }
}